using System.Drawing;
using System.Drawing.Printing;

namespace WorkerService1
{
    public class Worker(ILogger<Worker> logger) : BackgroundService
    {
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            string printFilePath = @"E:\Project\Test\WorkerService1\WorkerService1\output.pdf";
            try
            {
                // 检查文件是否存在
                if (!File.Exists(printFilePath))
                {
                    logger.LogError("文件不存在: {filePath}", printFilePath);
                    return;
                }
                logger.LogInformation("开始打印文件: {filePath}", printFilePath);
                PrintPdfUsingPrintDocument(printFilePath);
                logger.LogInformation("打印任务已提交");
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "打印过程中发生错误");
            }

            await Task.CompletedTask;
            logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
        }

        private static void PrintPdfUsingPrintDocument(string filePath)
        {
            PrintDocument pd = new();
            pd.PrintPage += (sender, e) =>
            {
                if (e.Graphics is null) return;
                Image img = Image.FromFile(filePath);
                e.Graphics.DrawImage(img, e.PageBounds);
            };
            pd.Print();
        }
    }
}
